package com.prizedraw.prize_draw.controller;

import cn.hutool.core.map.MapUtil;
import com.prizedraw.prize_draw.common.dto.SysMenuDto;
import com.prizedraw.prize_draw.common.lang.Result;
import com.prizedraw.prize_draw.entity.SysMenu;
import com.prizedraw.prize_draw.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;


/**
 * <p>
 *  动态菜单控制层
 * </p>
 *
 * @author czj666
 * @since 2021-09-07
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    /**
     * 获取导航栏权限
     * @param principal
     * @return
     */
    @GetMapping("/nav")
    public Result nav(Principal principal){
        SysUser sysUser = sysUserService.getByUserId(principal.getName());

        //获取该用户的权限
        String authorityInfo  = sysUserService.getUserAuthorityInfo(sysUser.getId());
        //这里不使用UserDetailServiceImpl中获取权限的方法，因为该方法把每一个字符串都封装成了一个权限对象
        //这里只需要普通的字符串权限数字
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        //获取导航栏权限
        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();
        return Result.succ(MapUtil.builder()
                .put("authoritys",authorityInfoArray)
                .put("nav",navs)
                .build()
        );
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:perm:list')")
    public Result list() {
        // 查询所有菜单，并将其转为父子关系的树形结构的json数据
        List<SysMenu> menus = sysMenuService.tree();
        return Result.succ(menus);
    }
}
